package ajaxjs.admin.PageEditor;

import javax.servlet.http.HttpServletRequest;

import ajaxjs.Util;
import ajaxjs.net.upload.Upload_HTTP;

public class Upload {
	private HttpServletRequest request;
	private ajaxjs.js.JsEngine js;
	public Upload(HttpServletRequest request){
		this.request = request;
		this.js = new ajaxjs.js.JsEngine();
	}
	
	/**
	 * 获取指定目录内的图片
	 * 目录有 folder 参数指定
	 * @return
	 */
	public String getImgList(){
		String folder = Util.Mappath(request, request.getParameter("folder"));
		java.io.File dir = new java.io.File(folder); 
		java.io.File[] files = dir.listFiles(); 
        
		java.util.List<String> json = new java.util.ArrayList<String>();
		
        if(files == null)return null;
        
        for (int i = 0; i < files.length; i++){
            if (files[i].isDirectory()){
            	continue;
            }else{ 
                final String strFileName = files[i].getName();
                if(strFileName.contains(".jpg") || strFileName.contains(".gif") || strFileName.contains(".png")){
                	
                	String el = js.parseObj(new Object() {  
            	        @SuppressWarnings("unused")
						public Boolean isOk = true;   
            	        @SuppressWarnings("unused")
						public String fileName = strFileName;
            	        @SuppressWarnings("unused")
						public String id = strFileName;
            	    });
                	
                	json.add(el);	
                }                   
            }
        }
        
        return "{result:[" + Util.stringJoin(json, ",") + "]}";
	}
	
	public String delFile(){
		String json = null;
		String file = Util.Mappath(request, request.getParameter("file"));
		
		if(new java.io.File(file).delete()){
			json = js.parseObj(new Object() {  
				@SuppressWarnings("unused")
				public Boolean isOk = true;
			});
		}else{
			json = js.parseObj(new Object() {  
				@SuppressWarnings("unused")
				public Boolean isOk = false;
			});
		}
		return json;
	} 
	
	public String uploadFile(){
		Upload_HTTP uploader = new Upload_HTTP(request);
		uploader.setSaveFolder(request.getParameter("folder").replace("/", "\\"));
		String[] arr = uploader.upload().split("\\\\");
		
		final String fileName = arr[arr.length - 1];
		
		return js.parseObj(new Object() {  
	        @SuppressWarnings("unused")
			public Boolean isOk = true;   
	        @SuppressWarnings("unused")
			public String filename = fileName;
	        @SuppressWarnings("unused")
			public String id = fileName;
	    });
	}
}
